package cn.demo.thread;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * 管道实现线程通信
 *
 * @author duxiaod
 * @date 2021/07/24 21:00
 **/
@Slf4j
public class Piped {

    public static void main(String[] args) throws IOException {
        //面向于字符 PipedInputStream 面向于字节
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader();

        //输入输出流建立连接
        writer.connect(reader);
        Thread t1 = new Thread(() -> {
            log.info("t1 running");
            try {
                for (int i = 0; i < 10; i++) {
                    writer.write(i+"");
                }
            }catch (Exception e){

            }finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            log.info("t2 running");
            int msg = 0;
            try {
                while ((msg = reader.read()) != -1) {
                    log.info("msg={}", (char) msg);
                }
            }catch (Exception e){

            }finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}
